package com.cch.android.activity;

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.cch.android.util.Constant;
import com.cch.android.util.MyLog;
import com.cch.android.util.contacts.Contacts;
import com.cch.android.util.contacts.Person;


public class ImageLocalActivity extends Activity implements OnClickListener{
	private ImageView imageView;
	private LinearLayout opeanimagelay,cameraimagelay;
	private Button homebtn;
	private AlertDialog myDialog;
	private Context mContext;
	private Contacts contact=null;
	private List<Person>  personList=null;
	private Bitmap imageBmp;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.photo_local);
		mContext = this;
		initView();
		
	}
    public void initView(){
    	imageView = (ImageView)findViewById(R.id.image_local_imageview);
    	changePic();
    }
	public void changePic() {
		LayoutInflater inflater = getLayoutInflater();
		View layout = inflater.inflate(R.layout.dialog_open, null);
		opeanimagelay = (LinearLayout)layout.findViewById(R.id.openimage);
		cameraimagelay = (LinearLayout)layout.findViewById(R.id.cameraimage);
		homebtn = (Button)layout.findViewById(R.id.home);
		opeanimagelay.setOnClickListener(this);
		cameraimagelay.setOnClickListener(this);
		homebtn.setOnClickListener(this);
		myDialog = new AlertDialog.Builder(ImageLocalActivity.this).create();
		myDialog.show();
		myDialog.getWindow().setContentView(layout);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == RESULT_OK) {
			if (requestCode == 0) {
				Uri uri = data.getData();
				// Log.e("uri", uri.toString());
				ContentResolver cr = this.getContentResolver();
				try {
					imageBmp = BitmapFactory.decodeStream(cr
							.openInputStream(uri));
					/* 将Bitmap设定到ImageView */
					imageView.setImageBitmap(imageBmp);
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			} else if (requestCode == 1) {
				try {
					super.onActivityResult(requestCode, resultCode, data);
					Bundle extras = data.getExtras();
					imageBmp = (Bitmap) extras.get("data");
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					imageBmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
//					byte[] mContent = baos.toByteArray();
				} catch (Exception e) {
					e.printStackTrace();
				}
				// 把得到的图片绑定在控件上显示
				imageView.setImageBitmap(imageBmp);
			}
			super.onActivityResult(requestCode, resultCode, data);
			
			imageView.setOnLongClickListener(new OnLongClickListener() {
				
				@Override
				public boolean onLongClick(View v) {
					MyLog.log("长按....");
				final String[] mItems = {getString(R.string.local_setbg),getString(R.string.local_setHead)};
					AlertDialog.Builder builder = new AlertDialog.Builder(mContext).setItems(mItems, new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
						//点击后弹出窗口选择了第几项
						switch (which) {
						case 0:
							AlertDialog.Builder builder = new AlertDialog.Builder(mContext).setIcon(R.drawable.icon)
							.setTitle(getString(R.string.local_setbg_if))
							.setPositiveButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichButton) {
							//这里添加点击确定后的逻辑
								try{
								     setWallpaper(imageBmp);
								     Toast toast = Toast.makeText(getApplicationContext(),
								    		 getString(R.string.local_setbg_succ), Toast.LENGTH_LONG);
								    	   toast.setGravity(Gravity.CENTER, 0, 0);
								    	   toast.show();
								 }catch(IOException e) {
									 Toast toast = Toast.makeText(getApplicationContext(),
											 getString(R.string.local_setbg_fail), Toast.LENGTH_LONG);
								    	   toast.setGravity(Gravity.CENTER, 0, 0);
								    	   toast.show();
					                    e.printStackTrace();
					             }
								 dialog.dismiss();
								 
							}
							}).setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int whichButton) {
							//这里添加点击确定后的逻辑
								dialog.dismiss();
							}
							});
							builder.create().show();
							
							break;
						case 1:
							 contact = new Contacts(mContext);
							personList = contact.getPerson();
							int personSize = personList.size();
							String [] personArr = new String[personSize];
							for(int i=0;i<personSize;i++)
							personArr[i] = personList.get(i).getName();
							AlertDialog.Builder builder2 = new AlertDialog.Builder(mContext).setItems(personArr, new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {
								//设置联系人头像
								//先截取图片大小
								boolean succesFlag = contact.setPersonPhotoBytes(mContext, Constant.Bitmap2Bytes(imageBmp), 
										personList.get(which).getId(), true);
								if(succesFlag){
									 Toast toast = Toast.makeText(getApplicationContext(),
											 getString(R.string.local_sethead_succ), Toast.LENGTH_LONG);
								    	   toast.setGravity(Gravity.CENTER, 0, 0);
								    	   toast.show();
								}else{
									 Toast toast = Toast.makeText(getApplicationContext(),
											 getString(R.string.local_sethead_fail), Toast.LENGTH_LONG);
								    	   toast.setGravity(Gravity.CENTER, 0, 0);
								    	   toast.show();
								}
								
							}
							});
							builder2.create().show();
							break;
						}
						}
						});
					builder.create().show();
					return false;
				}
			});
			
			
		}
	}
	@Override
	protected void onDestroy() {
		if (imageBmp != null) {
			imageBmp.recycle();
			System.gc();
			imageBmp=null;
		}
		super.onDestroy();
	}
	@Override
	public void onClick(View v) {
		myDialog.dismiss();
		switch (v.getId()) {
		case R.id.openimage:
			Intent getImage = new Intent(
					Intent.ACTION_GET_CONTENT);
			getImage.addCategory(Intent.CATEGORY_OPENABLE);
			getImage.setType("image/*");
			startActivityForResult(getImage, 0);
			break;
       case R.id.cameraimage:
    	   Intent getImageByCamera = new Intent(
			"android.media.action.IMAGE_CAPTURE");
	       startActivityForResult(getImageByCamera, 1);
			break;
       case R.id.home:
    	   backToHome();
    	   break;

		}
		
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			finish();
			break;

		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}
	private void backToHome(){
		finish();
		Intent intent = new Intent();
		intent.setClass(this, ImageMainActivity.class);
		startActivity(intent);
	}
}
